import { Component, Injector } from '@angular/core';
import { AppComponentBase } from '@abp/components';
import {
  AuditLogServiceProxy,
  AuditLogListDto,
} from '@abp/service-proxies/service-proxies';
import { AuditLogDetailComponent } from './audit-logs-detail/audit-log-detail.component';

@Component({
  templateUrl: './audi-log.component.html',
  styleUrls: ['./audi-log.component.less'],
})
export class AudiLogComponent extends AppComponentBase {
  /** 是否显示高级过滤 */
  advancedFiltersVisible = false;
  /** 模糊搜索的文本 */
  userName = '';
  serviceName: string;
  methodName: string;
  browserInfo: string;
  hasException: boolean = undefined;
  minExecutionDuration: number;
  maxExecutionDuration: number;
  startToEndDate = [];

  constructor(
    injector: Injector,
    private auditLogService: AuditLogServiceProxy,
  ) {
    super(injector);
  }

  ngOnInit(): void {
    this.searchData();
  }

  hasExceptionChange() {
    this.searchData();
  }

  dateRangeChange() {
    this.searchData();
  }

  /**
   * 刷新表格数据
   * @param args
   */
  refresh(): void {
    this.searchData();
  }

  sort(sort: { key: string; value: string }): void {
    this.tableHelper.sort = sort;
    this.searchData();
  }

  searchData(reset: boolean = false): void {
    if (reset) {
      this.tableHelper.pageIndex = 1;
    }
    this.tableHelper.isLoading = true;

    let startData;
    let endData;
    if (this.startToEndDate.length === 2) {
      startData =
        this.startToEndDate[0] === null ? undefined : this.startToEndDate[0];
      endData =
        this.startToEndDate[1] === null ? undefined : this.startToEndDate[1];
    }

    this.auditLogService
      .getAuditLogs(
        startData,
        endData,
        this.userName,
        this.serviceName,
        this.methodName,
        this.browserInfo,
        this.hasException,
        this.minExecutionDuration,
        this.maxExecutionDuration,
        this.tableHelper.getSorting(),
        this.tableHelper.getMaxResultCount(),
        this.tableHelper.getSkipCount(),
      )
      .subscribe(data => {
        this.tableHelper.isLoading = false;
        this.tableHelper.totalRecordsCount = data.totalCount;
        this.tableHelper.records = data.items;
      });
  }

  showDetails(item: AuditLogListDto) {
    let config = this.drawerConfig(
      '审计日志详情',
      AuditLogDetailComponent,
      {
        auditLog: item,
      },
      500,
    );
    const drawerRef = this.drawerService.create(config);

    drawerRef.afterOpen.subscribe(() => {});

    drawerRef.afterClose.subscribe(data => {
      if (data) {
        this.searchData();
      }
    });
  }
}
